package com.example.juejincheck.utils;

import javax.xml.transform.*;
import javax.xml.transform.stream.StreamResult;
import javax.xml.transform.stream.StreamSource;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.InputStream;

/**
 * @author yangkun
 * @description
 * @date 2023年01月30日 8:43
 */
public class ToHtmlUtils {
    /**
     * 根据传入的xsl字符串将xml字符串转化为对应的html字符串
     *
     * @param xml xml字符串
     * @param xsl xsl字符串
     * @return java.lang.String
     */
    public static String TransformXmlToHtml(String xml, String xsl) {
        try {
            //将xsl字符串转为文件流
            ByteArrayInputStream byteArrayInputStream = new ByteArrayInputStream(xsl.getBytes("GBK"));
            InputStream xslInputStream = byteArrayInputStream;

            //将xml字符串转为文件流
            ByteArrayInputStream byteArrayInputStream2 = new ByteArrayInputStream(xml.getBytes("GBK"));
            InputStream xmlInputStream = byteArrayInputStream2;

            Source xslSource = new StreamSource(xslInputStream);
            Source source = new StreamSource(xmlInputStream);
            ByteArrayOutputStream bytes = new ByteArrayOutputStream();
            Result result = new StreamResult(bytes);

            //转换xml
            TransformerFactory tFac = TransformerFactory.newInstance();
            Transformer t = tFac.newTransformer(xslSource);
            t.setOutputProperty(OutputKeys.ENCODING,"GBK");

            //返回html
            t.transform(source, result);
            return bytes.toString("GBK");
        } catch (Exception e) {
            e.printStackTrace();
        }
        return "";
    }
}
